//
//  ANHomeViewController.m
//  Ants
//
//  Created by ZHM on 16/3/15.
//  Copyright © 2016年 ZHM. All rights reserved.
//

#import "ANHomeViewController.h"
#import <CoreLocation/CoreLocation.h>
#import "UIBarButtonItem+item.h"
#import "HMOneViewController.h"
#import "ANProductViewController.h"
#import "ANNavigationVC.h"
#import "ANFindTool.h"

@interface ANHomeViewController ()<UITableViewDataSource,UITableViewDelegate,ANFindToolDelegate,CLLocationManagerDelegate>
@property (nonatomic, strong) UILabel *titleView;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *products;
@property (nonatomic, strong) NSArray *banners;
@property (nonatomic, assign) BOOL isFirstRunRefresh;

@property (nonatomic, assign) CGFloat newContentOffsetY;
@property (nonatomic, assign) CGFloat oldContentOffsetY;
@property (nonatomic, assign) CGFloat contentOffsetY;

@property (nonatomic, strong) ANFindTool *barTool;
@property (nonatomic, weak) UIView *taskbarViewBg;

@property (nonatomic, strong) ANProductGetParam *param;
//位置
@property (nonatomic, strong) CLLocation *location;
@property (nonatomic, strong) CLLocationManager *manager;
@end


@implementation ANHomeViewController

- (NSMutableArray *)products {
    if (!_products) {
        _products = [NSMutableArray array];
    }
    return _products;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    //定位
    [self positioning];
    
    _tableView = [[UITableView alloc] initWithFrame:ANKeyWindow.bounds style:UITableViewStyleGrouped];
    [self.view addSubview:_tableView];
    _isFirstRunRefresh = YES;
    //设置导航条左右按钮
    [self setUpNavgationBar];
    //配置TableView
    [self configureTableView];
    [self configureFindTool];
    //添加通知 监听删除消息
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(removeProduct:) name:@"RemoveProductCompletion" object:nil];
}
- (void)loadView {
    [super loadView];
    [[SDImageCache sharedImageCache] setShouldDecompressImages:NO];
    [[SDWebImageDownloader sharedDownloader] setShouldDecompressImages:NO];
}
- (void)removeProduct:(NSNotification *)notification {
    [_products enumerateObjectsUsingBlock:^(ANBDProduct * obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj.mlObjectId isEqualToString:notification.object]) {
            if (idx <= _param.skipNew) {
                _param.skipNew--;
            } else {
                _param.skipMore--;
            }
            [_products removeObject:obj];
            [self.tableView reloadData];
            *stop = YES;
        }
    }];
}
#pragma mark- SubViews Configuration

- (void)configureTableView {
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.tableFooterView = [[UIView alloc] init];
    self.tableView.tableFooterView.backgroundColor = [UIColor clearColor];
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 80.0;
}
- (void)configureFindTool {
    //工具条
    _barTool = [ANFindTool showWithTableView:self.tableView];
    _barTool.delegate = self;

    [self.view addSubview:_barTool];
}
- (void)configurePullToRefresh {
    _tableView.pullToRefreshView.arrowColor = [UIColor orangeColor];
    _tableView.pullToRefreshView.textColor = [UIColor orangeColor];
    [_tableView.pullToRefreshView setTitle:@"下拉以刷新" forState:SVPullToRefreshStateTriggered];
    [_tableView.pullToRefreshView setTitle:@"刷新完成" forState:SVPullToRefreshStateStopped];
    [_tableView.pullToRefreshView setTitle:@"玩命的加载中..." forState:SVPullToRefreshStateLoading];
}

- (void)addPullToRefresh {
    __weak typeof(self) weakSelf = self;
    _param = [ANProductGetParam param];
    _param.isDateSort = YES;
    [weakSelf.tableView addPullToRefreshWithActionHandler:^{
        [weakSelf insertRowAtTop];
    }];
    // 设置上拉加载更多
    [weakSelf.tableView addInfiniteScrollingWithActionHandler:^{
        [weakSelf insertRowAtBottom];
    }];
}
- (void)insertRowAtTop {
    [self configurePullToRefresh];
    self.tableView.showsInfiniteScrolling = NO;
    _param.isLoadNew = YES;
    [sharedWebService fetchProductsFromParam:_param completion :^(NSArray *products, BOOL isReachEnd, NSError *error) {
        execute_after_main_queue(0.4, ^{
            [self.tableView.pullToRefreshView stopAnimating];
        });
        self.tableView.showsInfiniteScrolling = YES;
        if (error) {
            if (error.code == 20002) {
                [SVProgressHUD showErrorWithStatus:NSLocalizedString(@"网络连接超时", nil)];
            } else {
                [SVProgressHUD showErrorWithStatus:NSLocalizedString(@"出错了", nil)];
                ANLog(@"error:%@",error);
            }
        } else {
            //ANLog(@"count=%ld",(long)products.count);
            if (products.count == 0) {
                [SVProgressHUD showErrorWithStatus:NSLocalizedString(@"无数据", nil)];
            }else {
                [products enumerateObjectsUsingBlock:^(ANBDProduct *obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    [self.products insertObject:obj atIndex:0];
                }];
                //记录起始位置
                if (_param.isDateSort) {
                    _param.newsDate = [_products[0] createdAt];
                    _param.moreDate = [_products[_products.count - 1] createdAt];
                }
                if (_param.isLocationSort || _param.isPriceSort) {
                    _param.skipMore += products.count;
                }
            }
        }
        [self.tableView reloadData];
    }];
}
- (void)findTool:(ANFindTool *)findTool didSelectSection:(NSInteger)section stringArray:(NSArray *)array {
    switch (section) {
        case 0://地区
            //porductSortWithAdd
            [self findPorductWithAddress:array];
            break;
        case 1://类别
            [self findPorductWithCategory:array[0]];
            break;
        case 2://排列
            [self porductSortWithNumber:array[0]];
            break;
    }
}
- (void)porductSortWithNumber:(NSNumber*)sortStr {
    
    switch ([sortStr integerValue]) {
        case 0:
            [_products removeAllObjects];
            _param.skipMore = 0;
            _param.skipNew = 0;
            _param.newsDate = nil;
            _param.moreDate = nil;
            _param.isPriceSort = NO;
            _param.isLocationSort = NO;
            _param.isDateSort = YES;
            _param.sortKey = @"createdAt";
            _param.isAscending = NO;
            [self.tableView triggerInfiniteScrolling];
            break;
        case 1:
            [_products removeAllObjects];
            _param.skipMore = 0;
            _param.skipNew = 0;
            _param.newsDate = nil;
            _param.moreDate = nil;
            _param.isPriceSort = NO;
            _param.isDateSort = NO;
            _param.isLocationSort = YES;
            _param.sortKey = @"location";
            //服务器默认返回降序
            //_param.isAscending = YES;
            _param.sortmoreValue = _location;
            [self.tableView triggerInfiniteScrolling];
            break;
        case 2:
            [_products removeAllObjects];
            _param.skipMore = 0;
            _param.skipNew = 0;
            _param.newsDate = nil;
            _param.moreDate = nil;
            _param.isLocationSort = NO;
            _param.isDateSort = NO;
            _param.isPriceSort = YES;
            _param.isAscending = YES;
            _param.sortKey = @"price";
            [self.tableView triggerInfiniteScrolling];
            break;
        case 3:
            [_products removeAllObjects];
            _param.skipMore = 0;
            _param.skipNew = 0;
            _param.newsDate = nil;
            _param.moreDate = nil;
            _param.isLocationSort = NO;
            _param.isDateSort = NO;
            _param.isPriceSort = YES;
            _param.isAscending = NO;
            _param.sortKey = @"price";
            [self.tableView triggerInfiniteScrolling];
            break;
    }
}
- (void)findPorductWithCategory:(id)obj {
    if ([obj isKindOfClass:[NSString class]]) {
        [_products removeAllObjects];
        _param.skipMore = 0;
        _param.skipNew = 0;
        _param.newsDate = nil;
        _param.moreDate = nil;
        _param.relationKey = nil;
        //触发下拉刷新
        [self.tableView triggerInfiniteScrolling];
        return;
    }
    [_products removeAllObjects];
    _param.skipMore = 0;
    _param.skipNew = 0;
    _param.newsDate = nil;
    _param.moreDate = nil;
    _param.relationKey = @"product";
    ANBDProductCategory *cateory = (ANBDProductCategory *)obj;
    _param.relationObj = (BmobObject*)cateory.bmObject;
    [self.tableView triggerInfiniteScrolling];
}
- (void)findPorductWithAddress:(NSArray *)array {
    if ([array[0] isEqualToString:@"全国"]) {
        [_products removeAllObjects];
        _param.skipMore = 0;
        _param.skipNew = 0;
        _param.newsDate = nil;
        _param.moreDate = nil;
        _param.address = nil;
        [self.tableView triggerInfiniteScrolling];
        return;
    }
    [_products removeAllObjects];
    _param.skipMore = 0;
    _param.skipNew = 0;
    _param.newsDate = nil;
    _param.moreDate = nil;
    _param.address = array;
    [self.tableView triggerInfiniteScrolling];
}

- (void)insertRowAtBottom {
    _param.isLoadNew = NO;
    [self configurePullToRefresh];
    [sharedWebService fetchProductsFromParam:_param completion:^(NSArray *products, BOOL isReachEnd, NSError *error) {
        execute_after_main_queue(0.4, ^{
            [self.tableView.infiniteScrollingView stopAnimating];
        });
        //到达数据终点 停止
        self.tableView.showsInfiniteScrolling = !isReachEnd;
        if (!error) {
            //NSLog(@"count=%ld",(unsigned long)products.count);
            if (products.count == 0) {
                [SVProgressHUD showErrorWithStatus:NSLocalizedString(@"无数据", nil)];
            }else {
                [self.products addObjectsFromArray:products];
                //记录起始位置
                if (_param.isDateSort) {
                    _param.newsDate = [_products[0] createdAt];
                    _param.moreDate = [_products[_products.count - 1] createdAt];
                }
                if (_param.isLocationSort || _param.isPriceSort) {
                    _param.skipMore += products.count;
                }
            }
        } else {
            if (error.code == 20002) {
                [SVProgressHUD showErrorWithStatus:NSLocalizedString(@"网络连接超时", nil)];
            } else {
                [SVProgressHUD showErrorWithStatus:NSLocalizedString(@"出错了", nil)];
                ANLog(@"error:%@",error);
            }
        }
        [self.tableView reloadData];
    }];
}
//        if (_products.count) {
//            //本地加载
//            NSPredicate *predicate = [NSPredicate predicateWithFormat:@"createdAt<=%@",param.formDate];
//            [ANBDProduct MR_findAllSortedBy:param.sortKey ascending:param.isAscending withPredicate:<#(NSPredicate *)#> inContext:<#(NSManagedObjectContext *)#>];
//        }

- (void)viewDidLayoutSubviews {
    if (_isFirstRunRefresh) {
        [self addPullToRefresh];
        self.isFirstRunRefresh = NO;
        //触发下拉刷新
        [self.tableView triggerInfiniteScrolling];
    }
}

#pragma mark --设置导航条
- (void)setUpNavgationBar {
    // 左边
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem barButtonItemWithImage:[UIImage imageNamed:@"location"] highImage:[UIImage imageNamed:@"location"] target:self action:@selector(friendsearch) forControlEvents:UIControlEventTouchUpInside];
    //右边
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem barButtonItemWithImage:[UIImage imageNamed:@"navigationbar_pop"] highImage:[UIImage imageNamed:@"navigationbar_pop_highlighted"] target:self action:@selector(pop) forControlEvents:UIControlEventTouchUpInside];
    self.titleView = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 120, 40)];
    //self.titleView.text = @"不变";
    self.titleView.textAlignment = NSTextAlignmentCenter;
    self.navigationItem.titleView = self.titleView;
}

//右边
- (void)pop {
    HMOneViewController *oneVC = [[HMOneViewController alloc] init];
    oneVC.view.backgroundColor = [UIColor purpleColor];
    //当PUSH时候就会隐藏底部条
    oneVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:oneVC animated:YES];
}

// 左边
- (void)friendsearch {
    if (!_location) {
        [self positioning];
    }
    [SVProgressHUD showWithStatus:@"定位中..."];
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    __weak typeof(self) weakSelf = self;
    [geocoder reverseGeocodeLocation:_location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        if (placemarks.count == 0 || error) {
            ANLog(@"错误:%@",error);
            [SVProgressHUD dismiss];
            return;
        }
        [SVProgressHUD dismiss];
        CLPlacemark *placemark = placemarks.lastObject;
        [weakSelf.barTool changecityBtnTitleWithString:placemark.locality];
        ANLog(@"定位---------:%@",placemark.locality);
        [weakSelf findPorductWithAddress:@[placemark.locality]];
    }];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.products.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ANProductTableViewCell *cell = [ANProductTableViewCell cellWithTableView:tableView];
    ANBDProduct *oneProduct = self.products[indexPath.row];
    cell.product = oneProduct;
    CLLocationDistance meters = [_location distanceFromLocation:(CLLocation *)oneProduct.location];
    if (meters >= 1000) {
        cell.distanceLabel.text = [NSString stringWithFormat:@"距离:%0.0f公里",meters/1000];
    } else {
        cell.distanceLabel.text = [NSString stringWithFormat:@"距离:%0.0f米",meters];
    }
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    ANBDProduct *product = self.products[indexPath.row];
    ANProductViewController *productVC = [[ANProductViewController alloc] init];
    productVC.product = product;
    //取消隐藏效果
    [_barTool recoveryBar];
    //当PUSH时候就会隐藏底部条
    productVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:productVC animated:YES];
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if (_barTool.IsMoving) return;
    _newContentOffsetY = scrollView.contentOffset.y;
    if (_newContentOffsetY < _oldContentOffsetY && _oldContentOffsetY < _contentOffsetY&& _barTool.barIsHidden && scrollView.contentOffset.y < scrollView.contentSize.height - ANKeyWindow.height) {
        [_barTool recoveryBar];
    }
    if (_newContentOffsetY > _oldContentOffsetY && _oldContentOffsetY > _contentOffsetY && !_barTool.barIsHidden && scrollView.contentOffset.y > -64 && _products.count > 6) {
        [_barTool hiddenBar];
    }
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    _contentOffsetY = scrollView.contentOffset.y;
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    _oldContentOffsetY = scrollView.contentOffset.y;
}



- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewAutomaticDimension;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 2;
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    //取消隐藏效果
    [_barTool recoveryBar];
    [_taskbarViewBg removeFromSuperview];
}
#pragma mark --定位代理方法
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    CLLocation *location = [locations lastObject];
    _location = location;
    ANLog(@"定位:%@",location);
    [self.manager stopUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
    ANLog(@"定位失败啦:%@",error);
}
- (void)positioning {
        CLLocationManager *manager = [[CLLocationManager alloc] init];
        manager.delegate = self;
        manager.distanceFilter = 10;
        manager.desiredAccuracy = kCLLocationAccuracyBest;
        if(iOS8Later) {
            [manager requestAlwaysAuthorization];
        }
        if (iOS9Later) {
            manager.allowsBackgroundLocationUpdates = YES;
        }
    _manager = manager;
    [manager startUpdatingLocation];
}
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [_barTool removeFromSuperview];
    [[SDImageCache sharedImageCache] setShouldDecompressImages:YES];
    [[SDWebImageDownloader sharedDownloader] setShouldDecompressImages:YES];
    NSLog(@"%s",__func__);
}
@end
